package geektime.concurrent.part1;

import java.util.concurrent.locks.ReentrantLock;

public class MyFairLock2{
    
    private ReentrantLock lock = new ReentrantLock(true);

    class CompeteThread extends Thread {
        @Override
        public void run() {
            while(true) {
                while (true) {
                    try {
                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + " hold");
                    } finally {
                        System.out.println(Thread.currentThread().getName() + " release");
                        lock.unlock();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        MyFairLock2 myFairLock2 = new MyFairLock2();
        // 使用同一个MyFairLock2的实例来创建线程，这样依赖可以保证lock为同一把锁，于是就可以营造出四个线程竞争同一把锁的场景
        myFairLock2.new CompeteThread().start();
        myFairLock2.new CompeteThread().start();
        myFairLock2.new CompeteThread().start();
        myFairLock2.new CompeteThread().start();
    }
}
